package pl.shenlon.poker.cards.evaluation;

import pl.shenlon.poker.cards.Card;
import pl.shenlon.poker.cards.CardUtils;
import pl.shenlon.poker.cards.Hand;
import pl.shenlon.poker.cards.deck.PokerDeck;

public class WinChanceEvaluator {
	private static WinChanceEvaluator instance;

	public static WinChanceEvaluator getInstance() {
		if (instance == null) {
			instance = new WinChanceEvaluator();
		}
		return instance;
	}

	private final HandRankEvaluator handEvaluator;

	private WinChanceEvaluator() {
		handEvaluator = HandRankEvaluator.getInstance();
	}

	public double evaluateWinningChance(Hand playerHand, Hand table) {
		int hands = 0, wins = 0;
		Hand opponentHand = new Hand(playerHand.getCardsCount());
		Hand combinedHand = CardUtils.joinHands(playerHand, table);
		HandRank rank = handEvaluator.evaluateHand(playerHand, table);
		Card[] cards = new PokerDeck().getCardsInDeck();

		for (int i = cards.length - 1; i >= 0; i--) {
			if (combinedHand.containsCard(cards[i])) {
				continue;
			}
			opponentHand.setCard(0, cards[i]);
			for (int j = i - 1; j >= 0; j--) {
				if (combinedHand.containsCard(cards[j])) {
					continue;
				}
				opponentHand.setCard(1, cards[j]);
				HandRank opponentHandRank = handEvaluator.evaluateHand(
						opponentHand, table);
				hands++;
				int comparision = rank.compareTo(opponentHandRank);
				if (comparision > 0) {
					wins++;
				} else if (comparision == 0
						&& rank.toString().startsWith("HIGH_CARD")) {
					if (Integer.compare(playerHand.getRanksValue(),
							opponentHand.getRanksValue()) > 0) {
						wins++;
					}
				}
			}
		}
		return ((double) wins) / hands;
	}
}